package cn.slahser.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import cn.slahser.model.Reply;

public class ReplyService {
	private Connection conn = null;

	public ReplyService(Connection conn) {
		this.conn = conn;
	}

	public void add(Reply obj) throws Exception {
		PreparedStatement st = conn
				.prepareStatement("insert into reply(text,type,userid,titleid) values(?,?,?,?)");

		st.setString(1, obj.getText());
		st.setString(2, obj.getType());
		st.setInt(3, obj.getUserid());
		st.setInt(4, obj.getTitleid());
		if (st.executeUpdate() <= 0) {
			throw new Exception();
		}
	}

	public void set(Reply obj) throws Exception {
		PreparedStatement st = conn
				.prepareStatement("update reply set  text =?,type =?,sendtime =?,userid =?,titleid =? where reid=?");
		st.setString(1, obj.getText());
		st.setString(2, obj.getType());
		st.setString(3, obj.getSendtime());
		st.setInt(4, obj.getUserid());
		st.setInt(5, obj.getTitleid());
		st.setInt(6, obj.getReid());
		if (st.executeUpdate() <= 0) {
			throw new Exception();
		}
	}

	public void delete(int obj) throws Exception {
		PreparedStatement st = conn
				.prepareStatement("delete from reply where reid=?");
		st.setObject(1, obj);

		if (st.executeUpdate() <= 0) {
			throw new Exception();
		}
	}

	public Vector<Reply> findKey(int key) throws Exception {
		return findColumnName("reid", key);
	}

	public static final String TXT = "text";
	public static final String TYPE = "type";
	public static final String SENDTIME = "sendtime";
	public static final String USERID = "userid";
	public static final String TITLEID = "titleid";

	public Vector<Reply> findColumnName(String cname, Object value)
			throws Exception {
		PreparedStatement pst = conn
				.prepareStatement("SELECT * FROM reply WHERE " + cname + "=?");
		pst.setObject(1, value);
		ResultSet re = pst.executeQuery();
		Vector<Reply> list = new Vector<Reply>();
		while (re.next()) {
			Reply obj1 = new Reply();
			obj1.setReid(re.getInt("reid"));
			obj1.setText(re.getString("text"));
			obj1.setType(re.getString("type"));
			obj1.setSendtime(re.getString("sendtime"));
			obj1.setUserid(re.getInt("userid"));
			obj1.setTitleid(re.getInt("titleid"));
			list.add(obj1);
		}
		return list;
	}

	public Vector<Reply> findAll() throws Exception {
		PreparedStatement pst = conn.prepareStatement("SELECT * FROM reply");
		ResultSet re = pst.executeQuery();
		Vector<Reply> list = new Vector<Reply>();
		while (re.next()) {
			Reply obj1 = new Reply();
			obj1.setReid(re.getInt("reid"));
			obj1.setText(re.getString("text"));
			obj1.setType(re.getString("type"));
			obj1.setSendtime(re.getString("sendtime"));
			obj1.setUserid(re.getInt("userid"));
			obj1.setTitleid(re.getInt("titleid"));
			list.add(obj1);
		}
		return list;
	}

}
